#!/usr/bin/python
# -*- coding: utf-8 -*-
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import UserCreationForm
from django.core import serializers
from django.core.cache import cache
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.loader import render_to_string
from django.utils import simplejson 
from django.views.generic.simple import direct_to_template
from djangotoolbox.http import JSONResponse
from labapp import homeControl
from labapp.models import Statistiques
import logging
from django.utils import simplejson
import random
from labapp.models import Delinquance

MEMCACHE_COORDINATE = 'coordinate'


def writeJson(request):
  logging.debug('Handler : Write Bar Json')
  bars = barControl.getAllBars(request)
  json_response = serializers.serialize("json", bars)
  return HttpResponse(json_response)

def routePage(request, page, pageName = None):
  for i in range(1, 5):
    statistiques = Statistiques()
    statistiques.name = 'Data' + str(i)
    statistiques.value = i * 10
    statistiques.save()

def routePage(request, page, pageName = None):
  if page is None:
    page = 'NO PAGE'
  logging.debug('Handler : Route page ' + page + ' user: ' + request.user.username)
  return direct_to_template(request, 'labapp/index.html',
      {'page': page})

def indexPage(request):

    departments = ['Tous','Ain',"Aisne","Allier","Alpes-de-Haute-Provence","Hautes-Alpes","Alpes-Maritimes","Ardèche","Ardennes",    "Ariège","Aube"    ,"Aude"    ,"Aveyron","Bouches-du-Rhône"    ,"Calvados"    ,"Cantal"    ,"Charente"    ,"Charente-Maritime"    ,"Cher"    ,"Corrèze"    ,"Corse-du-Sud"    ,"Haute-Corse"    ,"Côte-d'Or"    ,"Côtes-d'Armor"    ,"Creuse"    ,"Dordogne","Doubs",    "Drôme"    ,"Eure",    "Eure-et-Loir",    "Finistère"    ,"Gard"    ,"Haute-Garonne"    ,"Gers",    "Gironde",    "Hérault",    "Ille-et-Vilaine"    ,"Indre",    "Indre-et-Loire",    "Isère",    "Jura"    ,"Landes"    ,"Loir-et-Cher",    "Loire"    ,"Haute-Loire"    ,"Loire-Atlantique",    "Loiret"    ,"Lot",    "Lot-et-Garonne",    "Lozère",    "Maine-et-Loire",    "Manche"    ,"Marne",    "Haute-Marne"    ,"Mayenne",    "Meurthe-et-Moselle",    "Meuse"    ,"Morbihan"    ,"Moselle",    "Nièvre",    "Nord",    "Oise"    ,"Orne",    "Pas-de-Calais"    ,"Puy-de-Dôme"    ,"Pyrénées-Atlantiques",    "Hautes-Pyrénées",    "Pyrénées-Orientales",    "Bas-Rhin"    ,"Haut-Rhin"    ,"Rhône"    ,"Haute-Saône"    ,"Saône-et-Loire","Sarthe"    ,"Savoie"    ,"Haute-Savoie",    "Paris",    "Seine-Maritime"    ,"Seine-et-Marne"    ,"Yvelines"    ,"Deux-Sèvres"    ,"Somme",    "Tarn",    "Tarn-et-Garonne"    ,"Var"    ,"Vaucluse"    ,"Vendée"    ,"Vienne"    ,"Haute-Vienne"    ,"Vosges"    ,"Yonne"    ,"Territoire de Belfort"    ,"Essonne"    ,"Hauts-de-Seine",    "Seine-Saint-Denis"    ,"Val-de-Marne",    "Val-d Oise"]
    years =  ['2002','2003','2004','2005','2006']
    data = {};
    for i in years:
        tous = 0
        d = {}
        obj = Delinquance.objects.filter(year = i)
        for j in obj:
           d[j.name] = int(j.value) 
        data[i] = d

    return direct_to_template(request, 'labapp/index.html',
      {'years': simplejson.dumps(years),'departments': simplejson.dumps(departments),'data': simplejson.dumps(data)})

def remplirBase(request):
    
    departments = ['Tous','Ain',"Aisne","Allier","Alpes-de-Haute-Provence","Hautes-Alpes","Alpes-Maritimes","Ardèche","Ardennes",    "Ariège","Aube"    ,"Aude"    ,"Aveyron","Bouches-du-Rhône"    ,"Calvados"    ,"Cantal"    ,"Charente"    ,"Charente-Maritime"    ,"Cher"    ,"Corrèze"    ,"Corse-du-Sud"    ,"Haute-Corse"    ,"Côte-d'Or"    ,"Côtes-d'Armor"    ,"Creuse"    ,"Dordogne","Doubs",    "Drôme"    ,"Eure",    "Eure-et-Loir",    "Finistère"    ,"Gard"    ,"Haute-Garonne"    ,"Gers",    "Gironde",    "Hérault",    "Ille-et-Vilaine"    ,"Indre",    "Indre-et-Loire",    "Isère",    "Jura"    ,"Landes"    ,"Loir-et-Cher",    "Loire"    ,"Haute-Loire"    ,"Loire-Atlantique",    "Loiret"    ,"Lot",    "Lot-et-Garonne",    "Lozère",    "Maine-et-Loire",    "Manche"    ,"Marne",    "Haute-Marne"    ,"Mayenne",    "Meurthe-et-Moselle",    "Meuse"    ,"Morbihan"    ,"Moselle",    "Nièvre",    "Nord",    "Oise"    ,"Orne",    "Pas-de-Calais"    ,"Puy-de-Dôme"    ,"Pyrénées-Atlantiques",    "Hautes-Pyrénées",    "Pyrénées-Orientales",    "Bas-Rhin"    ,"Haut-Rhin"    ,"Rhône"    ,"Haute-Saône"    ,"Saône-et-Loire","Sarthe"    ,"Savoie"    ,"Haute-Savoie",    "Paris",    "Seine-Maritime"    ,"Seine-et-Marne"    ,"Yvelines"    ,"Deux-Sèvres"    ,"Somme",    "Tarn",    "Tarn-et-Garonne"    ,"Var"    ,"Vaucluse"    ,"Vendée"    ,"Vienne"    ,"Haute-Vienne"    ,"Vosges"    ,"Yonne"    ,"Territoire de Belfort"    ,"Essonne"    ,"Hauts-de-Seine",    "Seine-Saint-Denis"    ,"Val-de-Marne",    "Val-d Oise"]
    years =  ['2002','2003','2004','2005','2006']
    data = {};
    for i in years:
        tous = 0
        d = {}
        for j in departments:
            if(j!="Tous"):
                deliq = Delinquance()
                deliq.name = j
                deliq.year = i
                v = random.randint(1000,1000000)
                deliq.value = v
                deliq.save()
                d[j] = v
                tous = tous + v

        deliq = Delinquance()
        deliq.name = 'Tous'
        deliq.year = i
        deliq.value = tous
        deliq.save()
        d["Tous"] = tous
        data[i] = d
        
    return direct_to_template(request, 'labapp/remplirBase.html',{'data': simplejson.dumps(data)})

def remplirBase1(request):
    
    departments = ['Tous','Ain',"Aisne","Allier","Alpes-de-Haute-Provence","Hautes-Alpes","Alpes-Maritimes","Ardèche","Ardennes",    "Ariège","Aube"    ,"Aude"    ,"Aveyron","Bouches-du-Rhône"    ,"Calvados"    ,"Cantal"    ,"Charente"    ,"Charente-Maritime"    ,"Cher"    ,"Corrèze"    ,"Corse-du-Sud"    ,"Haute-Corse"    ,"Côte-d'Or"    ,"Côtes-d'Armor"    ,"Creuse"    ,"Dordogne","Doubs",    "Drôme"    ,"Eure",    "Eure-et-Loir",    "Finistère"    ,"Gard"    ,"Haute-Garonne"    ,"Gers",    "Gironde",    "Hérault",    "Ille-et-Vilaine"    ,"Indre",    "Indre-et-Loire",    "Isère",    "Jura"    ,"Landes"    ,"Loir-et-Cher",    "Loire"    ,"Haute-Loire"    ,"Loire-Atlantique",    "Loiret"    ,"Lot",    "Lot-et-Garonne",    "Lozère",    "Maine-et-Loire",    "Manche"    ,"Marne",    "Haute-Marne"    ,"Mayenne",    "Meurthe-et-Moselle",    "Meuse"    ,"Morbihan"    ,"Moselle",    "Nièvre",    "Nord",    "Oise"    ,"Orne",    "Pas-de-Calais"    ,"Puy-de-Dôme"    ,"Pyrénées-Atlantiques",    "Hautes-Pyrénées",    "Pyrénées-Orientales",    "Bas-Rhin"    ,"Haut-Rhin"    ,"Rhône"    ,"Haute-Saône"    ,"Saône-et-Loire","Sarthe"    ,"Savoie"    ,"Haute-Savoie",    "Paris",    "Seine-Maritime"    ,"Seine-et-Marne"    ,"Yvelines"    ,"Deux-Sèvres"    ,"Somme",    "Tarn",    "Tarn-et-Garonne"    ,"Var"    ,"Vaucluse"    ,"Vendée"    ,"Vienne"    ,"Haute-Vienne"    ,"Vosges"    ,"Yonne"    ,"Territoire de Belfort"    ,"Essonne"    ,"Hauts-de-Seine",    "Seine-Saint-Denis"    ,"Val-de-Marne",    "Val-d Oise"]
    years =  ['2007','2008','2009','2010']
    data = {};
    for i in years:
        tous = 0
        d = {}
        for j in departments:
            if(j!="Tous"):
                deliq = Delinquance()
                deliq.name = j
                deliq.year = i
                v = random.randint(1000,1000000)
                deliq.value = v
                deliq.save()
                d[j] = v
                tous = tous + v

        deliq = Delinquance()
        deliq.name = 'Tous'
        deliq.year = i
        deliq.value = tous
        deliq.save()
        d["Tous"] = tous
        data[i] = d
        
    return direct_to_template(request, 'labapp/remplirBase1.html',{'data': simplejson.dumps(data)})

def delinquancePage(request):
  return direct_to_template(request, 'labapp/delinquance.html')

def linePage(request):
  return direct_to_template(request, 'labapp/Line.html')

def tablePage(request):
  return direct_to_template(request, 'labapp/Table.html')

def SPLinePage(request):
  return direct_to_template(request, 'labapp/SPLine.html')

def AreaPage(request):
  return direct_to_template(request, 'labapp/Area.html')

def AreaSplinePage(request):
  return direct_to_template(request, 'labapp/AreaSpline.html')

def PiePage(request):
  return direct_to_template(request, 'labapp/Pie.html')

def BarPage(request):
  return direct_to_template(request, 'labapp/Bar.html')

def ColumnPage(request):
  return direct_to_template(request, 'labapp/Column.html')

def ScatterPage(request):
  return direct_to_template(request, 'labapp/Scatter.html')

def MapPage(request):
  return direct_to_template(request, 'labapp/Map.html')

def Slides(request):
  return direct_to_template(request, 'slides.html', {'value': -3000} )

def Slides2(request):
  return direct_to_template(request, 'slides2.html', {'value': -3000} )

def responsiveDesign(request):
  return direct_to_template(request, 'responsiveDesign.html', {'value': -3000} )

def saveCoordinate(request):
  latitude = request.POST['latitude']
  longitude = request.POST['longitude']
  logging.debug('Handler : save coordinate' + longitude + ' and ' + latitude)
#  cache.add(MEMCACHE_COORDINATE, latitude + '_' + longitude)
  request.session['coordinate_latitude'] = latitude 
  request.session['coordinate_longitude'] = longitude
  json_response = simplejson.dumps({"success" : "OK"})
  return HttpResponse(json_response)
#  return writeBarsJson(request)
  
def routePage2(request, pageName):
  logging.debug('Handler : route ' + pageName)
  return routePage(request, 'page2', pageName)

def loginView(request):
  username = request.POST['username']
  password = request.POST['password']

  user = authenticate(username=username, password=password)
  if user is not None:
    login(request, user)
    logging.debug('=======================================345345' + profileControl.userToJson(user)) 
    
    json_response = simplejson.dumps({"success" : "OK"})
    return HttpResponse(json_response)
  else:
    json_response = simplejson.dumps({'error' : 'no user'})
    logging.debug('=======================================345345' + json_response) 
    return HttpResponse(json_response)
